package rcs34.android.AndroidRC;

import rcs34.android.AndroidRC.Receivers.WifiStateReceiver;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

public class Activity_Main extends Activity implements Handler.Callback {
  private Button startButton;
  private Handler handler;
  private Messenger networkStateMessenger;
  private WifiStateReceiver wifiStateReceiver;
  private WifiStateReceiver wifiNetStateReceiver;
  private TextView wifiLabel;
  private TextView wifiAddr;
  private Button wifiEnable;
  private TextView authNote;
  private TextView serverStatus;
  private TextView socketsCount;
  private Drawable shapeRedButton;
  private Drawable shapeGreenButton;
  private Activity_Main aThis;
  private Messenger toServerMessenger;
  private ServiceConnection mConnection;
  private boolean serverRunning = false;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    aThis = this;
    setContentView(R.layout.activitymain);
    wifiLabel = (TextView) findViewById(R.id.netinfolabel);
    wifiAddr = (TextView) findViewById(R.id.netinfoaddress);
    serverStatus = (TextView) findViewById(R.id.mainvaluestatus);
    socketsCount = (TextView) findViewById(R.id.mainvaluesockets);
    wifiEnable = (Button) findViewById(R.id.mainbuttonwifi);
    startButton = (Button) findViewById(R.id.mainbuttonstartstop);
    authNote = (TextView) findViewById(R.id.mainauthnote);
    shapeRedButton = GApp.resources.getDrawable(R.drawable.button_red);
    shapeGreenButton = GApp.resources.getDrawable(R.drawable.button_green);
    handler = new Handler(this);
    // GApp.serviceStatusMessenger = new Messenger(handler);
    networkStateMessenger = new Messenger(handler);
    wifiStateReceiver = new WifiStateReceiver(networkStateMessenger,
        WifiStateReceiver.MSG_WIFI_STATE_CHANGED);
    wifiNetStateReceiver = new WifiStateReceiver(networkStateMessenger,
        WifiStateReceiver.MSG_WIFI_NET_CHANGED);
    handleStartStop(null);
  }
  
  public void onResume() {
    super.onResume();
    registerReceiver(wifiNetStateReceiver, new IntentFilter(
        WifiManager.NETWORK_STATE_CHANGED_ACTION));
    registerReceiver(wifiNetStateReceiver, new IntentFilter(
        WifiManager.RSSI_CHANGED_ACTION));
    registerReceiver(wifiStateReceiver, new IntentFilter(
        WifiManager.WIFI_STATE_CHANGED_ACTION));
    mConnection = new ServiceConnection() {
      public void onServiceConnected(ComponentName className, IBinder service) {
        toServerMessenger = new Messenger(service);
        Message message = new Message();
        message.arg1 = AndroidRCServer.MSG_CLIENT_ADD;
        message.arg2 = aThis.hashCode();
        message.replyTo = new Messenger(handler);
        try {
          toServerMessenger.send(message);
        } catch (RemoteException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      
      public void onServiceDisconnected(ComponentName className) {
        toServerMessenger = null;
      }
    };
    bindService(new Intent(this, AndroidRCServer.class), mConnection,
        Context.BIND_AUTO_CREATE);
    updateWifiState();
    updateNetworkState();
    updateSockets();
    updateIps();
  }
  
  public void onPause() {
    super.onPause();
    unregisterReceiver(wifiNetStateReceiver);
    unregisterReceiver(wifiStateReceiver);
    if (toServerMessenger != null) {
      Message message = new Message();
      message.arg1 = AndroidRCServer.MSG_CLIENT_DEL;
      message.arg2 = aThis.hashCode();
      try {
        toServerMessenger.send(message);
      } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      unbindService(mConnection);
      if (!serverRunning) {
        Intent intent = new Intent(this, AndroidRCServer.class);
        stopService(intent);
      }
    }
  }
  
  public void handleStartStop(View _view) {
    Intent intent = new Intent(this, AndroidRCServer.class);
    startButton.setVisibility(View.INVISIBLE);
    if (serverRunning) {
      intent.putExtra(AndroidRCServer.KEY_OPERATION, AndroidRCServer.VAL_STOP);
    } else {
      intent.putExtra(AndroidRCServer.KEY_OPERATION, AndroidRCServer.VAL_START);
    }
    startService(intent);
  }
  
  public void handleEnableWifi(View _view) {
    WifiManager manager = (WifiManager) getSystemService(WIFI_SERVICE);
    manager.setWifiEnabled(true);
    wifiLabel.setText(getString(R.string.waitaminute));
  }
  
  public void handleManageAuth(View _view) {
    Intent intent = new Intent(this, Activity_IpAuth.class);
    startActivity(intent);
    Message message = new Message();
    message.arg1 = AndroidRCServer.MSG_CLEAR_NOTIFICATION;
    try {
      toServerMessenger.send(message);
    } catch (RemoteException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.activitymain, menu);
    return true;
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_main_settings:
      Intent i = new Intent(this, Activity_Preferences.class);
      startActivity(i);
      return true;
    default:
      return super.onOptionsItemSelected(item);
    }
  }
  
  private void updateWifiState() {
    WifiManager manager = (WifiManager) getSystemService(WIFI_SERVICE);
    if (manager.getWifiState() == WifiManager.WIFI_STATE_DISABLED) {
      wifiLabel.setText(getString(R.string.wifinotenabled));
      wifiEnable.setVisibility(View.VISIBLE);
      wifiAddr.setVisibility(View.INVISIBLE);
      startButton.setVisibility(View.INVISIBLE);
      serverStatus.setVisibility(View.INVISIBLE);
    } else {
      // wifiLabel.setText("");
      wifiEnable.setVisibility(View.INVISIBLE);
      wifiAddr.setVisibility(View.VISIBLE);
      startButton.setVisibility(View.VISIBLE);
      serverStatus.setVisibility(View.VISIBLE);
    }
  }
  
  private void updateNetworkState() {
    WifiManager manager = (WifiManager) getSystemService(WIFI_SERVICE);
    WifiInfo info = manager.getConnectionInfo();
    if (info != null && info.getNetworkId() >= 0) {
      String ssid = info.getSSID();
      if (ssid != null) {
        ssid = info.getSSID().replace("\"", "");
      } else {
        ssid = getString(R.string.uunknown);
      }
      wifiLabel.setText(ssid + "; " + info.getLinkSpeed()
          + WifiInfo.LINK_SPEED_UNITS + "; "
          + WifiManager.calculateSignalLevel(info.getRssi(), 6));
      int ipAddress = info.getIpAddress();
      String ip = String.format("%d.%d.%d.%d", (ipAddress & 0xff),
          (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff),
          (ipAddress >> 24 & 0xff));
      wifiAddr.setText(getString(R.string.ipaddress) + " " + ip);
    } else {
      wifiLabel.setText(getString(R.string.notconnected));
      wifiAddr.setText("");
    }
  }
  
  private void updateServerStatus() {
    if (serverRunning) {
      startButton.setBackgroundDrawable(shapeRedButton);
      startButton.setText(R.string.sstopserver);
      String status = getString(R.string.listeningon) + " ";
      status += "port " + AndroidRCServer.port;
      serverStatus.setText(status);
    } else {
      startButton.setBackgroundDrawable(shapeGreenButton);
      startButton.setText(R.string.sstartserver);
      serverStatus.setText(getString(R.string.sserverisnotrunning));
    }
    startButton.invalidate();
    serverStatus.invalidate();
  }
  
  /*private void updateServerFailure(String _failure) {
    if (_failure != null) {
      serverFailure.setText(_failure);
    } else {
      serverFailure.setText("");
    }
  }*/
  
  private void updateSockets() {
    socketsCount.setText(getString(R.string.activesockets) + " "
        + GApp.socketsOpened);
    socketsCount.invalidate();
  }
  
  private void updateIps() {
    authNote.setText(getText(R.string.ipsinregister) + " "
        + GApp.ipRegister.size());
    authNote.invalidate();
  }
  
  @Override
  public boolean handleMessage(Message _msg) {
    if (AndroidRCServer.pendingOperations < 1) {
      startButton.setVisibility(View.VISIBLE);
    }
    int status = _msg.arg1;
    switch (status) {
    case AndroidRCServer.MSG_TCP_STARTED:
      serverRunning = true;
      updateServerStatus();
      break;
    case AndroidRCServer.MSG_TCP_STOPPED:
      serverRunning = false;
      updateServerStatus();
      Intent intent = new Intent(this, AndroidRCServer.class);
      stopService(intent);
      break;
    case AndroidRCServer.MSG_TCP_BIND_FAIL:
      // updateServerFailure(_msg.getData().getString(AndroidRCServer.KEY_MESSAGE));
      break;
    case AndroidRCServer.MSG_CONNECTION_OPEN:
    case AndroidRCServer.MSG_CONNECTION_CLOSE:
      updateSockets();
      break;
    case WifiStateReceiver.MSG_WIFI_STATE_CHANGED:
      updateWifiState();
      break;
    case WifiStateReceiver.MSG_WIFI_NET_CHANGED:
      updateNetworkState();
      break;
    case AndroidRCServer.MSG_NEW_IP_REQUEST:
      updateIps();
      break;
    }
    return false;
  }
}
